package com.itheima.service.Impl;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.utils.DateUtils;
import com.itheima.dto.MessageDto;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.vto.OrderVto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public static final String ORDER_KEY = "预约验证码";
    public static final String LOGIN_KEY = "登录验证码";
    /**
     * 根据预约id查询预约信息
     * @param id
     * @return
     */
    public OrderVto findById(Integer id) {
        return orderMapper.findById(id);
    }

    /**
     * 客户端预约
     * @param messageDto
     * @return
     */
    public String order(MessageDto messageDto) {
        //1.用户不是会员，需要自动完成注册\
        int isVIP = 0;
        //获取验证码

        String code = String.valueOf(redisTemplate.opsForValue().get(ORDER_KEY+messageDto.getTelephone()));

        isVIP = orderMapper.QueryID(messageDto.getTelephone());
        if (isVIP !=0 ){
            //2.校验用户输入的验证码是否正确。
            if (messageDto.getValidateCode().equals(code)) {
              //  3. 预约日期的预约人数没有设置的话不能预约。
              int number = 0;
              number=orderMapper.ValidateOrderSetting(messageDto.getOrderDate());
              int numberOrder = 0;
              numberOrder = orderMapper.FindOrdered(messageDto.getOrderDate());
                if(number!=0){
                    //4. 预约日期是否已经约满，如果已经约满则无法预约。
                    if(number>numberOrder){
                        //5. 不能重复预约（同一个用户在同一天预约了同一个套餐）。
                        if (orderMapper.isExit(messageDto.getIdCard(),messageDto.getOrderDate())!=0){
                            return MessageConstant.HAS_ORDERED;
                        }else{
                            //6. 更新已预约人数
                            try {
                                Order order = Order.builder()
                                        .memberId(isVIP)
                                        .orderDate(DateUtils.parseString2Date(messageDto.getOrderDate().toString()))
                                        .orderType(messageDto.getTelephone()!=null?Order.ORDERTYPE_TELEPHONE:Order.ORDERTYPE_WEIXIN)
                                        .orderStatus(Order.ORDERSTATUS_NO)
                                        .setmealId(messageDto.getSetmealId())
                                        .build();
                                orderMapper.addOrder(order);
                                return MessageConstant.ORDER_SUCCESS;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }else {
                        return MessageConstant.ORDER_FULL;
                    }
                }else {
                    return MessageConstant.SELECTED_DATE_CANNOT_ORDER;
                }
            }else if(code==null){
                return MessageConstant.VALIDATECODE_OVERTIME;
            }else {
                return MessageConstant.VALIDATECODE_ERROR;
            }
        }else {
            //自动注册
            try {
                Member member = Member.builder()
                        .name(messageDto.getName())
                        .sex(messageDto.getSex())
                        .idCard(messageDto.getIdCard())
                        .phoneNumber(messageDto.getTelephone())
                        .regTime(DateUtils.parseString2Date(LocalDate.now().toString()))
                        .build();
                orderMapper.register(member);
                if (messageDto.getValidateCode().equals(code)) {
                    //  3. 预约日期的预约人数没有设置的话不能预约。
                    int number = 0;
                    number=orderMapper.ValidateOrderSetting(messageDto.getOrderDate());
                    int numberOrder = 0;
                    numberOrder = orderMapper.FindOrdered(messageDto.getOrderDate());
                    if(number!=0){
                        //4. 预约日期是否已经约满，如果已经约满则无法预约。
                        if(number>numberOrder){
                                //6. 更新已预约人数
                                try {
                                    Order order = Order.builder()
                                            .memberId(isVIP)
                                            .orderDate(DateUtils.parseString2Date(messageDto.getOrderDate().toString()))
                                            .orderType(messageDto.getTelephone()!=null?Order.ORDERTYPE_TELEPHONE:Order.ORDERTYPE_WEIXIN)
                                            .orderStatus(Order.ORDERSTATUS_NO)
                                            .setmealId(messageDto.getSetmealId())
                                            .build();
                                    orderMapper.addOrder(order);
                                    return MessageConstant.ORDER_SUCCESS;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                        }else {
                            return MessageConstant.ORDER_FULL;
                        }
                    }else {
                        return MessageConstant.SELECTED_DATE_CANNOT_ORDER;
                    }
                }else if(code==null){
                    return MessageConstant.VALIDATECODE_OVERTIME;
                }else {
                    return MessageConstant.VALIDATECODE_ERROR;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "预约报错了";
    }
}
